<?php

/**
 * 厅主管理-游戏开关
 * User: Tommy
 * Date: 2018/11/9
 * Time: 14:19
 */
namespace App\Services;

use App\Models\Hall;
use App\Models\HallPartnerConfig;
use App\Models\PartnerConfig;
use common\enum\CommonEnum;
use common\enum\MasterLogEnum;
use common\utils\SysCode;

class GameSwitchService
{

    /**
     * 游戏api配置列表
     * @return array
     */
    public static function getGamelist()
    {
        $data = PartnerConfig::select(['partner_id', 'game_type', 'partner_name'])->get()->toArray();
        return self::gamaType($data);
    }

    /**
     * 游戏api已授权数据
     * @param int $hallID
     * @return mixed
     */
    public static function getConfig(int $hallID)
    {
        $data = HallPartnerConfig::select(['partner_id', 'game_type', 'partner_name'])
            ->where(['hall_id' => $hallID])
            ->whereIn('status', [CommonEnum::DISABLE, CommonEnum::ENABLED])
            ->get()
            ->toArray();
        return self::gamaType($data);
    }

    /**
     * 游戏API分类
     * @param $gameArray
     * @return array
     */
    public static function gamaType($gameArray)
    {
        $gameData = [];
        foreach ($gameArray as $val) {
            $gameData[$val['game_type']][] = $val;
        }
        return $gameData;
    }



//    public static function getConfig(int $hallID)
//    {
//        return PartnerConfig::from("partner_config as pc")
//            ->leftJoin("hall_partner_config as hpc", function ($join) use ($hallID) {
//                $join->on('pc.partner_id', '=', 'hpc.partner_id')
//                    ->on('pc.game_type', '=', 'hpc.game_type')
//                    ->where(['hpc.hall_id' => $hallID]);
//            })
//            ->select([
//                'pc.id',
//                'pc.partner_id',
//                'pc.partner_name',
//                'pc.game_type',
//                DB::raw('IF(hpc.`status` IN(0, 1), 1, 0) AS `status`'),
//            ])
//            ->where(['pc.status' => CommonEnum::ENABLED])
//            ->get();
//    }

    /**
     * 修改游戏授权
     * @param $hallId
     * @param array $values
     * @return array
     * @throws \App\Exceptions\CustomException
     */
    public static function updateConfig($hallId, array $values)
    {
        //添加日志收集olg数据
        $data    = [];
        $oldData = HallPartnerConfig::where(['hall_id' => $hallId])->whereRaw("status != " . CommonEnum::DELETE)->get();
        if (!empty($oldData)) {
            $data['old'] = self::handleDara($oldData);
        }

        $ids = [];
        foreach ($values as $key => $value) {
            $hpc = HallPartnerConfig::where(['partner_id' => $value['partner_id'], 'game_type' => $value['game_type'], 'hall_id' => $hallId])->first();
            if (!$hpc) {
                $hpc = new HallPartnerConfig([
                    'hall_id'      => $hallId,
                    'partner_id'   => $value['partner_id'],
                    'partner_name' => $value['partner_name'],
                    'game_type'    => $value['game_type'],
                    'status'       => CommonEnum::DISABLE,
                    'pre_status'   => CommonEnum::DISABLE,
                ]);
            }
            if (!in_array($hpc['status'], [CommonEnum::DISABLE, CommonEnum::ENABLED])) {
                // 启动，厅主端全部恢复默认关闭状态
                $hpc['status']     = CommonEnum::DISABLE;
                $hpc['pre_status'] = CommonEnum::DISABLE;
            }
            if (!$hpc->save()) {
                error_exit(SysCode::HALL_GAME_UPDATE_ERROR);
            }
            $ids[] = $hpc['id'];//收集已授权的id
        }
        //关闭所有未授权的游戏API
        HallPartnerConfig::where(['hall_id' => $hallId])->whereNotIn('id', $ids)->update(['status' => CommonEnum::DELETE, 'pre_status' => CommonEnum::DELETE]);

        //添加日志收集new数据
        $newData = HallPartnerConfig::where(['hall_id' => $hallId])->whereRaw("status != " . CommonEnum::DELETE)->get();
        if (!empty($newData)) {
            $data['new'] = self::handleDara($newData);
        }
        $hall   = Hall::where(['id' => $hallId])->first();
        $remark = str_replace('{:name}', empty($hall['company_name']) ? '' : $hall['company_name'], MasterLogEnum::REMARK['hall_game_switch']);
        MasterLogService::writeMasterLog(MasterLogEnum::GAME_WARRANT, MasterLogEnum::SUCCESS, $remark, $data);
        return [];
    }

    /**
     * 写入日志转换数据
     * @param $arr
     * @return array
     */
    public static function handleDara($arr)
    {
        $oneData = [];
        foreach ($arr as $key => $value) {
            $oneData[$value['game_type']][] = $value['partner_name'];
        }
        $data = [];
        foreach ($oneData as $k => $val) {
            $data[CommonEnum::GAME_SUFFIX[$k]] = implode('、', $val);
        }
        return $data;
    }

}
